﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a publication rating.
    /// </summary>
    public class CreatePublicationRating : CreateRating
        <PublicationRatingEntity, PublicationCommentEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .IsVerified()
                    .Rule((ctx, uow) => ctx.Account(uow).EntityID == AccountID);
                yield return new SecurityPolicy()
                    .Rule((ctx, uow) => AccountID == 0);
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public PublicationRatingFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            var publication = uow.Execute(new GetPublication
            {
                ThrowsException = true,
                EntityID = HolderID
            }).Result;
            if(!publication.Flags.HasFlag(PublicationFlags.RatingAllowed))
                return Err.Of(this).NotAllowed();
            if(!uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("Allowed")
            }).ResultAs<Boolean>())
            {
                return Err.Of(this).NotAllowed();
            }

            var account = AccountID != 0 
                ? uow.Execute(new GetAccount
                {
                    ThrowsException = true,
                    EntityID = AccountID
                }).Result 
                : null;
            if(account == null)
            {
                if(!publication.Flags.HasFlag(PublicationFlags.AnonRatingAllowed))
                    return Err.Of(this).NotAllowed().Reason("Anon");
                if(!uow.Execute(new GetConfigParamValueByKey
                {
                    Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("AnonAllowed")
                }).ResultAs<Boolean>())
                {
                    return Err.Of(this).NotAllowed().Reason("Anon");
                }
            }

            byte valueMin = uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("Min")
            }).ResultAs<Byte>();
            if(Value < valueMin)
                return Err.Of<PublicationRatingEntity>().NotValid("Value");
            byte valueMax = uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("Max")
            }).ResultAs<Byte>();
            if(Value > valueMax)
                return Err.Of<PublicationRatingEntity>().NotValid("Value");

            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out PublicationRatingEntity result)
        {
            base.Work(uow, out  result);

            uow.Execute(new UpdatePublicationStats
            {
                EntityID = result.HolderID
            });

            try
            {
                uow.Execute(new EnqueuePublicationRatingNotification
                {
                    RatingID = result.EntityID,
                    RecipientID = uow.Execute(new GetPublication
                    {
                        ThrowsException = true,
                        EntityID = result.HolderID
                    }).Result.Author.Account.EntityID
                });
            }
            catch(Exception ex)
            {
                uow.Execute(new CreateLogRecordFromException
                {
                    Ex = ex
                });
            }
        }

        protected override void Construct(IUnitOfWork uow, PublicationRatingEntity entity)
        {
            base.Construct(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the publication rating.
    /// </summary>
    public class UpdatePublicationRating : UpdateRating<PublicationRatingEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public PublicationRatingFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override Err Validate(IUnitOfWork uow)
        {
            byte valueMin = uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("Min")
            }).ResultAs<Byte>();
            if(Value < valueMin)
                return Err.Of<PublicationRatingEntity>().NotValid("Value");
            byte valueMax = uow.Execute(new GetConfigParamValueByKey
            {
                Key = Par.In("Publishing").Of<PublicationRatingEntity>().Name("Max")
            }).ResultAs<Byte>();
            if(Value > valueMax)
                return Err.Of<PublicationRatingEntity>().NotValid("Value");
            return base.Validate(uow);
        }

        protected override void Work(IUnitOfWork uow, out PublicationRatingEntity result)
        {
            base.Work(uow, out result);
            uow.Execute(new UpdatePublicationStats
            {
                EntityID = result.HolderID
            });
        }

        protected override void Revise(IUnitOfWork uow, PublicationRatingEntity entity)
        {
            base.Revise(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the publication rating.
    /// </summary>
    public class DeletePublicationRating : DeleteRating<PublicationRatingEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("PBLSH");
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow)
        {
            int holderID = uow.Execute(new GetPublicationRating
            {
                ThrowsException = true,
                EntityID = EntityID
            }).Result.HolderID;

            base.Work(uow);

            uow.Execute(new UpdatePublicationStats
            {
                EntityID = holderID
            });
        }

        #endregion
    }

    /// <summary>
    /// Gets the publication rating by identifier.
    /// </summary>
    public class GetPublicationRating : GetEntity<PublicationRatingEntity>,
        IApiOperation
    {
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over publication rating collection.
    /// </summary>
    public class SearchPublicationRatings : SearchRatings<PublicationRatingEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchPublicationRatings()
        {
            SortDir = SortDirection.Ascending;
        }

        #endregion

        #region Properties


        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public PublicationRatingFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<PublicationRatingEntity> Build(IUnitOfWork uow, IQueryable<PublicationRatingEntity> query)
        {
            query = base.Build(uow, query);
            query = query.FilterByFlags(x => x.FlagsValue, (int)FlagMask);
            query = query.OrderBy(x => x.CreatedOn, SortDir);
            return query;
        }

        #endregion
    }

    #endregion

    #region __Notification__

    /// <summary>
    /// Enqueues a publication rating notification message.
    /// </summary>
    /// <remarks>
    /// Message template code: NPBLRTG
    /// Allowed tokens: [T:Recipient.EntityID], [T:Recipient.Guid], [T:Recipient.Email], [T:Recipient.Username],
    /// [T:PublicationRating.Publication.EntityID], [T:PublicationRating.Publication.RatingAverage],
    /// [T:PublicationRating.Publication.RatingCount], [T:PublicationRating.Publication.CommentCount],
    /// [T:PublicationRating.Publication.Title], [T:PublicationRating.Publication.Description],
    /// [T:PublicationRating.Account.EntityID], [T:PublicationRating.Account.Email],
    /// [T:PublicationRating.Account.Username], [T:PublicationRating.Account.Guid],
    /// [T:PublicationRating.EntityID], [T:PublicationRating.Value], [T:PublicationRating.CreatedOn],
    /// [T:PublicationRating.Publication.Code]
    /// </remarks>
    public class EnqueuePublicationRatingNotification : Operation<MessageEntity>
    {
        #region Properties

        /// <summary>
        /// Gets or sets the rating identifier.
        /// </summary>
        public int RatingID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the recipient account identifier.
        /// </summary>
        public int RecipientID
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out MessageEntity result)
        {
            var rating = uow.Execute(new GetPublicationRating
            {
                ThrowsException = true,
                EntityID = RatingID
            }).Result;
            var recipient = uow.Execute(new GetAccount
            {
                ThrowsException = true,
                EntityID = RecipientID
            }).Result;
            var usrLocale = recipient.LocalizationProfile;
            int utcOffset = usrLocale.TimeZone.UtcOffset;
            string dtFmt = usrLocale.Country.DateTimeFormat;
            var publication = uow.Execute(new GetPublication
            {
                EntityID = rating.HolderID
            }).Result;
            var t_publication = publication.Translation(usrLocale.Language.EntityID);

            result = uow.Execute(new CreateTemplatedMessageByCode
            {
                TemplateCode = "NPBLRTG",
                LanguageID = usrLocale.Language.EntityID,
                Replacements = new Dictionary<String, String>
                {
                    {"Recipient.EntityID", recipient.EntityID.ToString()},
                    {"Recipient.Email", recipient.Email},
                    {"Recipient.Username", recipient.Username},
                    {"Recipient.Guid", recipient.Guid.ToString()},
                    {"PublicationRating.Publication.EntityID", publication.EntityID.ToString()},
                    {"PublicationRating.Publication.RatingAverage", publication.RatingAverage.ToString()},
                    {"PublicationRating.Publication.RatingCount", publication.RatingCount.ToString()},
                    {"PublicationRating.Publication.CommentCount", publication.CommentCount.ToString()},
                    {"PublicationRating.Publication.Code", publication.Code},
                    {"PublicationRating.Publication.Title", t_publication != null 
                        ? t_publication.Title 
                        : String.Empty},
                    {"PublicationRating.Publication.Description", t_publication != null 
                        ? t_publication.Description 
                        : String.Empty},
                    {"PublicationRating.Account.EntityID", rating.Account != null 
                        ? rating.Account.EntityID.ToString() 
                        : String.Empty},
                    {"PublicationRating.Account.Username", rating.Account != null 
                        ? rating.Account.Username 
                        : String.Empty},
                    {"PublicationRating.Account.Email", rating.Account != null 
                        ? rating.Account.Email 
                        : String.Empty},
                    {"PublicationRating.Account.Guid", rating.Account != null 
                        ? rating.Account.Guid.ToString() 
                        : String.Empty},
                    {"PublicationRating.EntityID", rating.EntityID.ToString()},
                    {"PublicationRating.Value", rating.Value.ToString()},
                    {"PublicationRating.CreatedOn", rating.CreatedOn.ToLocal(utcOffset).ToStringByFmt(dtFmt)}
                },
                To = recipient.Email,
                Flags = MessageFlags.Active
            }).Result;
        }

        #endregion
    }

    #endregion
}
